// server/index.js
const express = require('express')
const cors = require('cors')

function createServer() {
  const app = express()

  // 中间件
  app.use(cors())
  app.use(express.json())
  app.use(express.urlencoded({ extended: true }))

  // 路由
  app.get('/api/hello', (req, res) => {
    res.json({ msg: 'Hello from Express inside Electron!' })
  })

  app.post('/test', (req, res) => {
    console.log('body:', req.body)
    res.json({ msg: 'Hello from Express inside Electron!' })
  })

  return app
}

// 启动服务
export default function startServer(port = 3030) {
  return new Promise((resolve, reject) => {
    const app = createServer()
    const server = app.listen(port, () => {
      console.log(`Express server running at http://localhost:${port}`)
      resolve(server)
    })
    server.on('error', reject)
  })
}
